import Vue from 'vue';
import VueRouter from 'vue-router';
import { constRoutes, routes } from './routes';
import store from '@/store/modules/user';

Vue.use(VueRouter);

let menuList = store.state.menuList;
const router = new VueRouter({
  routes: [ ...menuList],
});

// const router = new VueRouter({
//   routes: [
//     ...constRoutes,
//     ...routes
//   ],
// });
router.beforeEach((to, from, next) => {
  if (menuList.toString() !== store.state.menuList.toString()) {
    menuList = store.state.menuList;
    // 添加新路由
    router.matcher = new VueRouter().matcher;
    router.addRoutes(store.state.menuList);
  }
  document.title = `${to.meta?.title || ''} | ${process.env.VUE_APP_TITLE}`;
  // let userInfo = sessionStorage.getItem('userInfo');
  // let userInfo = store.userInfo;
  if (store.state.token) {
    if (to.path === '/login' || to.path === '/register') {
      next({ path: '/' });
    } else {
      next();
    }
  } else {
    console.log(to.path)
    if (to.meta.needLogin) {
      next({ path: '/login' });
    } else {
      if (to.path === '/login') {
        next();
      } else {
        if (to.path === '/welcome') {
          next();
        } else {
          next('/welcome');
        }

      }

    }
  }
});

export default router;
